package com.samuel.blog.dao;

import com.samuel.blog.utils.GenericsUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class BaseDaoImpl<T, E extends Serializable> extends SqlSessionDaoSupport implements BaseDao<T, E> {

	@Autowired  
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {  
        super.setSqlSessionFactory(sqlSessionFactory);  
    }
	
	@SuppressWarnings("unchecked")
    public String getNampSpace() {  
		Class<T> clazz = (Class<T>)GenericsUtils.getSuperClassGenricType(this.getClass());  
        String simpleName = clazz.getSimpleName() + "Dao";  
        return simpleName;  
    }  
    
	@Override
    public T selectByPrimaryKey(E id) {
		return getSqlSession().selectOne((this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                : this.getNampSpace()) + "selectByPrimaryKey", id);
	}

	@Override
	public int updateByPrimaryKeySelective(T entity) {
		return getSqlSession().update((this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                : this.getNampSpace()) + "updateByPrimaryKeySelective", entity);
	}

	@Override
	public List<T> selectByMap(Map<String, Object> map) {
		return getSqlSession().selectList((this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                : this.getNampSpace()) + "selectByMap", map);
	}

	@Override
	public int insertSelective(T entity) {
		return getSqlSession().insert(  
                (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                        : this.getNampSpace()) + "insertSelective", entity);  
	}

	@Override
	public int insert(T entity) {
		return getSqlSession().insert(  
                (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                        : this.getNampSpace()) + "insert", entity);  
	}

	@Override
	public int deleteByPrimaryKey(E id) {
		return getSqlSession().delete(  
                (this.getNampSpace().contains("Entity") ? this.getNampSpace().replace("Entity", "")  
                        : this.getNampSpace()) + "deleteByPrimaryKey", id); 
	}

}
